import Koa from 'koa'
import Router from 'koa-router'
import bodyParser from 'koa-bodyparser'
import cors from '@koa/cors'
import mysql from 'mysql2/promise'
const pool = mysql.createPool({
    database: 'Bookvue',
    user: 'root',
    password: '123456',
    host: 'localhost'
})
const app = new Koa()
const router = new Router()
app.use(cors())
app.use(bodyParser())
router.get('/book', async (ctx) => {
    const  {keyword}  = ctx.request.query || ''
    let query = 'select * from BookVue'
    let params = []
    if (keyword) {
        query += ' where name like ? or author like ?'
        params = [`%${keyword}%`,`%${keyword}%`]
    } 
    const  [rows] = await pool.query(query, params)
    ctx.body = rows
    
})
router.post('/book', async (ctx) => {
    const { name, author } = ctx.request.body
    const [results] = await pool.query(
        'INSERT into BookVue (name,author) VALUES (?,?)',
        [name, author]
    )
    ctx.body = { id: results.insertId }
})
router.delete('/book/:id', async (ctx) => {
    await pool.query('delete from BookVue where id =?', [ctx.params.id])
    ctx.body = '1'
})
router.get('/book/:id',async(ctx)=>{
    const [rows] = await pool.query('select * from BookVue where id = ?',[ctx.params.id])
    ctx.body=rows
})
router.put('/book/:id',async(ctx)=>{
    const {name,author} = ctx.request.body
    const [results] = await pool.query(
        'update BookVue set name = ?,author =? where id = ?',
        [name,author,ctx.params.id]
    )
    ctx.body=results
})
app.use(router.routes())
app.listen(8080, () => {
    console.log('http://localhost:8080');
})
